# !/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
from datetime import timedelta

import flask
import threading
from flask import request, template_rendered, current_app, session
from flask.json import jsonify
from flask_login import logout_user, login_user, user_logged_in, current_user

from __init__ import create_app
from model.SystemModel import TUserModel
from util import LogUtil
from util.SessionUtil import Mast_be_login_decorator
from util.StrUtil import encode_md5

# 创建Flask应用
app = create_app(__name__)


@user_logged_in.connect_via(app)
def log_user_logged(sender, user, **extra):
    """
    用户登录成功后调用的方法
    :param sender:
    :param user:
    :param extra:
    :return:
    """
    current_app.logger.info("用户:[{}]登录成功!!!!!!!!!!!!!!!!!!!!!".format(user.name))


@template_rendered.connect_via(app)
def log_template_renders(sender, template, context, **extra):
    """
    模板渲染成功后调用此方法
    :param sender:
    :param template:    即渲染成功的模板对象，包含模板名称等...
    :param context:     渲染模板的一些参数
    :param extra:
    :return:
    """
    current_app.logger.info('模板:[{}]渲染成功!! 参数：[{}] %s'.format(template.filename, context))


@app.route("/login/", methods=["POST"])
def do_login():
    username = request.form.get("username")
    password = request.form.get("password")

    LogUtil.info("username:{}".format(username))
    LogUtil.info("password:{}".format(password))

    # 1.根据username获得用户
    user = TUserModel.get_user_by_username(username)
    if user != None:
        if user.password == encode_md5(password):
            login_user(user)
            # 设置登录时效为10分钟
            session.permanent = True
            app.permanent_session_lifetime = timedelta(minutes=10)
            flask.flash("用户登录成功!!!")
            return jsonify(success=True, msg="登录成功")
        else:
            return jsonify(success=False, msg="您输入密码错误!")
    else:
        return jsonify(success=False, msg="您输入用户不存在!")


@app.route("/session/", methods=["POST"])
def get_session():
    LogUtil.info("=======================================================")
    LogUtil.info("测试和户是否登录...")
    if current_user.is_authenticated:
        LogUtil.info("用户{}已经登录....".format(current_user.name))
        return jsonify(success=True, username=current_user.name)
    else:
        LogUtil.info("用户没有登录....")
        LogUtil.info("=======================================================")
        return jsonify(success=False)


@app.route("/logout/", methods=["GET"])
@Mast_be_login_decorator
def logout():
    """
    用户退出登录
    :return:
    """
    LogUtil.info("用户{}退出登录!!!!".format(current_user.name))
    logout_user()
    result = {"success": True}
    return json.dumps(result)


@app.errorhandler(404)
def page_not_found(e):
    return jsonify(success=False, msg="错误码:404,请求地址无效!")


@app.errorhandler(500)
def internal_server_error(e):
    return jsonify(success=False, msg="错误码:500,服务器内部异常，请联系管理员!")


def application(env, start_response):
    app.run()


# if __name__ == '__main__':
#     app.run()
